package com.mocoop.plugin.ajax;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.google.gson.Gson;
import com.mocoop.activity.MocoopTabHost.MocoopTabHostListener;
import com.mocoop.biz.SyncDataBiz;
import com.mocoop.commom.MyTaskCallBack;
import com.mocoop.dao.AjaxWorkerDao;
import com.mocoop.dao.AjaxWorkerDaoImp;
import com.mocoop.entity.AjaxInfo;
import com.mocoop.entity.AjaxInfo.SQLOperation;
import com.mocoop.entity.AjaxInfo.UploadAttachmentFilesInfo;
import com.mocoop.entity.AjaxInfo.FileProgress;
import com.mocoop.jfqc.MainActivity;
import com.mocoop.jfqc.R;
import com.mocoop.plugin.MocoopPlugin;

import android.annotation.SuppressLint;

import android.util.Log;
import android.view.View;

@SuppressLint("NewApi")
public class AjaxWorkerPlugin extends MocoopPlugin {
	@Override
	public boolean execute(final String action, final CordovaArgs args,
			final CallbackContext callbackContext) throws JSONException {

//		runOnUiThread(new Runnable() {
//			@Override
//			public void run() {
//				if (getActivity().isNetworkConnected()) {
//					getActivity().getCurrentView().getNetStatusClues()
//							.setVisibility(View.GONE);
//				} else {
//					getActivity().getCurrentView().getNetStatusClues()
//							.setVisibility(View.VISIBLE);
//				}
//			}
//		});
		try {
			if (action.equals("requestURL")) {
				Log.d("RZZ", "callbackContext.success");
				AjaxWorker ajaxWorker = new AjaxWorker(getActivity(),
						getUserID());

				AjaxInfo ajaxInfo = new AjaxInfo();
				ajaxInfo.setRequestData(args.getString(1));
				ajaxInfo.setMethod(args.getString(2));
				ajaxInfo.setUrl(args.getString(0));
				ajaxWorker.request(ajaxInfo, new MyTaskCallBack() {

					@Override
					public void onSuccess(Object obj) {
						if (obj instanceof Exception) {
							callbackContext.error(obj.toString());
						} else {
							callbackContext.success((JSONObject) obj);
						}

					}
				}

				);

			} else if (action.equals("requestToAjax")) {
				requestToAjax(args, callbackContext);
			} else if (action.equals("loadAndSave")) {
				loadAndSave(args, callbackContext);
			} else if (action.equals("autoRequest")) {
				autoRequest();
			} else if (action.equals("autoRequestByIDs")) {
				autoRequestByIDs(args, callbackContext);
			} else if (action.equals("getAllProgress")) {
				getAllProgress(callbackContext);
			} else if (action.equals("messageCountController")) {
				((MocoopTabHostListener) cordova.getActivity())
						.messageCountController(args.getString(0),
								args.getString(1));
			}
		} catch (Exception e) {
			e.printStackTrace();
			callbackContext.error("error");
		}

		return true;
	}

	/**
	 * 注意 ： 所有有用到的表 都在com.mocoop.biz.CheckFirstRunBiz中
	 * 
	 * @param List
	 *            <String> 表名数组
	 * @return 结束调用callbackContext.success(); 并且更改title状态
	 *         先根据表名去http://110.80.35.58:23806/init/tab_Order/100000048/0/10
	 *         并且更改title状态 下载数据 再根据json_pk和lastupdatetime判断是否更新
	 * */
	public void loadAndSave(CordovaArgs args,
			final CallbackContext callbackContext) throws JSONException {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				getActivity()
						.getCurrentView()
						.getTitleStauts()
						.setText(
								getActivity().getResources().getString(
										R.string.titleRequestClues));
				getActivity().getCurrentView().showTitleStatus();
			}
		});

		SyncDataBiz syncDataBiz = new SyncDataBiz();
		syncDataBiz.setSyncAllDataCallBack(new SyncDataBiz.SyncDataCallBack() {
			@Override
			public void onSuccess(int batchCount) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						getActivity()
								.getCurrentView()
								.getTitleStauts()
								.setText(
										getActivity().getResources().getString(
												R.string.titleClues));
						getActivity().getCurrentView().hideTitleStatus();
					}
				});

				callbackContext.success();
			}
		});
		JSONArray jsonArray = args.getJSONArray(0);
		List<String> tableNames = new ArrayList<String>();
		for (int i = 0; i < jsonArray.length(); i++) {
			tableNames.add(jsonArray.getString(i));
		}
		syncDataBiz.loadDataByList(getActivity(), tableNames, getUserID());
	}

	/**
	 * @param args
	 *            .getJSONArray(0); 传入一个包含需要请求的ajaxWoker表的id数组 查询ajaxWoker表
	 *            开始执行请求 流程与requestToAjax一样
	 * */
	public void autoRequestByIDs(CordovaArgs args,
			final CallbackContext callbackContext) throws JSONException {
		AjaxWorkerDao ajaxWorkerDao = new AjaxWorkerDaoImp(getActivity(),
				getUserID());
		String sql = "";
		JSONArray jsonArray = args.getJSONArray(0);
		for (int i = 0; i < jsonArray.length(); i++) {
			sql += jsonArray.getString(i);
			if (i != jsonArray.length() - 1) {
				sql += ",";
			}
		}
		List<AjaxInfo> list = ajaxWorkerDao.findUnfinishedAjaxByIDs(sql);
		for (AjaxInfo ajaxInfo : list) {
			new AjaxWorker(getActivity(), getUserID())
					.executeRequestBiz(ajaxInfo);
		}
	}

	/**
	 * @param null 查询ajaxWorker表 提交所有需要提交的请求 提交流程与requestToAjax一样
	 * */
	public void autoRequest() {
		AjaxWorkerDao ajaxWorkerDao = new AjaxWorkerDaoImp(getActivity(),
				getUserID());
		List<AjaxInfo> list = ajaxWorkerDao.findUnfinishedAjax();
		AjaxWorker ajaxWorker = new AjaxWorker(getActivity(), getUserID());
		for (AjaxInfo ajaxInfo : list) {
			try {
				ajaxWorker.executeRequestBiz(ajaxInfo);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 *            .getJSONObject(0) = AjaxInfo
	 *            可以去看AjaxInfo那个实体类，如果ajaxInfo中有内置对象全部以json的形式存在数据库 先插入数据库
	 *            callback.success({"result":true,"ajaxID":""}); ajax的状态有
	 *            waiting uploading success failed 开始执行请求 通知
	 *            javascript:basic.eventNotification('{"type",
	 *            "ajaxStarted","ajaxID":""}');
	 *            如果有附件先做附件上传，每上传一张图片就执行insertImgFile 请求结束更改数据库 通知
	 *            javascript:basic.eventNotification('{"type",
	 *            "ajaxCompleted","ajaxID":""}');
	 * */

	public void requestToAjax(final CordovaArgs args,
			final CallbackContext callbackContext) throws JSONException {

		AjaxWorkerDao ajaxWorkerDao = new AjaxWorkerDaoImp(getActivity(),
				getUserID());
		JSONObject jsonObject = args.getJSONObject(0);
		AjaxInfo ajaxInfo = new AjaxInfo();

		ajaxInfo.setMethod(jsonObject.getString("HTTPMethod"));
		ajaxInfo.setUrl(jsonObject.getString("URL"));
		ajaxInfo.setRequestData(jsonObject.getString("requestData"));
		ajaxInfo.setExtra(jsonObject.getString("extra"));
		ajaxInfo.setMatchIDs(jsonObject.getString("matchIDs"));
		ajaxInfo.setNoticePages(jsonObject.getString("noticePages"));

		SQLOperation sqlOperation = new AjaxInfo.SQLOperation();
		JSONObject sqlObj = jsonObject.getJSONObject("SQLOperation");
		sqlOperation.setSQLOfAjaxCompleted(sqlObj
				.getString("SQLOfAjaxCompleted"));
		sqlOperation.setSQLOfAjaxStarted(sqlObj.getString("SQLOfAjaxStarted"));
		try {
			sqlOperation.setSQLOfAjaxSuccess(sqlObj
					.getString("SQLOfAjaxSuccess"));
		} catch (JSONException e) {
			sqlOperation.setSQLOfAjaxSuccess("");
		}
		try {
			sqlOperation.setSQLOfAjaxException(sqlObj
					.getString("SQLOfAjaxException"));
		} catch (JSONException e) {
			sqlOperation.setSQLOfAjaxException("");
		}
		ajaxInfo.setSqlOperation(sqlOperation);

		try {
			JSONArray jsonArray = jsonObject
					.getJSONArray("uploadAttachmentFilesInfo");
			List<UploadAttachmentFilesInfo> list = new ArrayList<AjaxInfo.UploadAttachmentFilesInfo>();
			if (jsonArray.length() > 0) {

				for (int i = 0; i < jsonArray.length(); i++) {
					UploadAttachmentFilesInfo attachmentFilesInfo = new UploadAttachmentFilesInfo();
					attachmentFilesInfo.setOriginalFileKey(jsonArray
							.getJSONObject(i).getString("originalFileKey"));
					attachmentFilesInfo.setOriginalFilePath(jsonArray
							.getJSONObject(i).getString("originalFilePath"));
					attachmentFilesInfo.setThumbnailFileKey(jsonArray
							.getJSONObject(i).getString("thumbnailFileKey"));
					attachmentFilesInfo.setThumbnailFilePath(jsonArray
							.getJSONObject(i).getString("thumbnailFilePath"));

					insertImgFile(ajaxWorkerDao,
							attachmentFilesInfo.getOriginalFileKey(),
							attachmentFilesInfo.getOriginalFilePath());
					insertImgFile(ajaxWorkerDao,
							attachmentFilesInfo.getThumbnailFileKey(),
							attachmentFilesInfo.getThumbnailFilePath());
					list.add(attachmentFilesInfo);
				}
			}
			ajaxInfo.setUploadAttachmentFilesInfo(list);
		} catch (JSONException e) {

		}

		ajaxInfo.setBeginTime(new Date().getTime());

		long id = ajaxWorkerDao.save(ajaxInfo);
		ajaxInfo.setId((int) id);

		JSONObject object = new JSONObject();
		object.put("result", true);
		object.put("ajaxID", id);
		callbackContext.success(object);
		new AjaxWorker(getActivity(), getUserID()).executeRequestBiz(ajaxInfo);
	}

	/**
	 * @param AjaxWorkerDao
	 * @param fileKey
	 *            上传的key
	 * @param filePath
	 *            图片所在路径
	 * */
	private void insertImgFile(AjaxWorkerDao ajaxWorkerDao, String fileKey,
			String filePath) {
		ajaxWorkerDao
				.execute(
						"Insert Into T_ImgFilePaths ([FImgFileKey],[FImgFilePath]) values(?,?);",
						new String[] { fileKey, filePath });
	}

	public void getAllProgress(CallbackContext callbackContext) {
		Map<String, Float> map = new HashMap<String, Float>();
		Map<String, FileProgress> mapProgress = AjaxWorker.mapProgress;
		for (String key : mapProgress.keySet()) {
			FileProgress progress = mapProgress.get(key);
			float currentProgress = 0, totalProgress = 0;
			if (progress.isOnlyThumbnail()) {
				currentProgress = progress.getThumbnailCurrentProgress();
				totalProgress = progress.getThumbnailCurrentProgress();
			} else if (progress.getOriginTotalProgress() > 1.0f) {
				currentProgress = progress.getThumbnailCurrentProgress()
						+ progress.getOriginCurrentProgress();
				totalProgress = progress.getThumbnailTotalProgress()
						+ progress.getOriginTotalProgress();
			}

			// if (currentProgress == totalProgress) {
			// AjaxWorker.actionProgress(3, progress);
			// continue;
			// }

			float result = 0.0f;
			if (currentProgress != result) {
				result = (float) currentProgress * 100 / totalProgress;
				result = (float) Math.floor(result);
			}
			map.put(progress.getProgressID(), result);

		}
		// Log.d("RZZ", mapProgress.toString());
		callbackContext.success(new Gson().toJson(map));
	}

}
